package com.lw.nio.channel.socketChannel;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author LW
 * @2021/9/12 19:23
 */
public class ServerSocketChannelDemo {
    public static void main(String[] args) throws Exception {
        //端口号设置
        int port = 8888;

        //创建一个buffer
        ByteBuffer buf = ByteBuffer.wrap("hello nio".getBytes());

        //ServerSocketChannel
        ServerSocketChannel ssc = ServerSocketChannel.open();

        //绑定
        ssc.socket().bind(new InetSocketAddress(port));

        //设置非阻塞模式
        ssc.configureBlocking(false);

        //一直监听是否有新的连接传入，或有没有新的SocketChannel对象创建
        while (true) {
            System.out.println("正在等待连接");
            SocketChannel sc = ssc.accept();
            //非阻塞时，当没有传入连接时，会立即返回null
            if(sc == null) {
                System.out.println("null");
                Thread.sleep(2000);
            }else{
                System.out.println("连接来自："+sc.socket().getRemoteSocketAddress());
                buf.rewind();//指针指向0===现在要开始操作了
                sc.write(buf);
                sc.close();
            }
        }

    }
}
